﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Text;
using Chat.Helpers;
using ChatLibrary.ChatDTOs;

namespace Chat.Hubs
{
    public class ChatHub : Hub
    {
        public void Register(string userName)
        {
            var newUser = new User(userName);
            UsersManager.Users.Add(Context.ConnectionId, newUser);

            var usersList = UsersManager.GetUsersList();

            Clients.Caller.registered(usersList);
            Clients.Others.newUserJoined(newUser, usersList);
        }

        public void SendMessage(string userName, string message)
        {
            var callerUser = UsersManager.Users[Context.ConnectionId];
            var newMessage = new Message(message, callerUser);
            Clients.All.newMessage(newMessage);
        }

        public override Task OnDisconnected()
        {
            var connectionId = Context.ConnectionId;
            var callerUser = UsersManager.Users[Context.ConnectionId];
            UsersManager.Users.Remove(connectionId);

            var usersList = UsersManager.GetUsersList();

            Clients.Others.userLoggedOut(callerUser, usersList);

            return base.OnDisconnected();
        }
    }
}